package cn.edu.ecnu.gis.client.gadgets;


import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.ui.HTML;
import cn.edu.ecnu.gis.client.GoogleFeedRequest;
import cn.edu.ecnu.gis.client.GoogleFeedRequestHandler;
import cn.edu.ecnu.gis.client.model.Gadget;
import cn.edu.ecnu.gis.client.model.GadgetClass;
import cn.edu.ecnu.gis.client.model.UserPref;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.ImageBundle;

public class WeatherGadget  extends Gadget implements GoogleFeedRequestHandler{
	
	public static class Class extends GadgetClass {
		public static UserPref location = new UserPref("Location","10001");
		public Class(){
			super("Weather",true);
			addUserPref( location );
		}
		public Gadget newGadget(){
			return new WeatherGadget(this);
		}
	}
	
	private HTML body = new HTML();
	protected WeatherGadget(Class c){
		super(c);
		initWidget( body );
		setStyleName( "Weather" );
		refresh();
	}
	
	public void refresh(){
		body.setHTML("");
		String url = "http://xml.weather.yahoo.com/forecastrss?p=" +
		getUserPrefValue( Class.location );
		GoogleFeedRequest.get( url,  this );
	}
	
	public void onRequestComplete( String result ){
		JSONObject feed = (JSONObject) JSONParser.parse( result );
		JSONArray entries = (JSONArray) feed.get("entries");
		if( entries.size() > 0 ){
			JSONObject item = (JSONObject)entries.get(0);
			JSONString content = (JSONString) item.get("content");
			body.setHTML(content.stringValue());
		}
	}
	
	public void onRequestFailed( String error ){
		body.setHTML(error);
	}
public interface BoundImage extends ImageBundle {

        AbstractImagePrototype inbox();
    }

   
    public AbstractImagePrototype getBoundImage() {
        BoundImage images = (BoundImage) GWT.create(BoundImage.class);
        return images.inbox();
    }
}